<template>
  <div class="check-patient-page">
    <el-card shadow="hover" class="patient-card">
      <template #header>
        <div class="card-header">当前患者检查申请</div>
      </template>
      <div v-if="checkRequest">
        <el-descriptions :column="3" border size="small">
          <el-descriptions-item label="申请ID">{{ checkRequest.id }}</el-descriptions-item>
          <el-descriptions-item label="挂号ID">{{ checkRequest.registerId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ patient.realName || checkRequest.patientName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="病历号">{{ patient.caseNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ patient.age || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ patient.gender || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ checkRequest.checkState }}</el-descriptions-item>
          <el-descriptions-item label="检查信息" :span="2">{{ checkRequest.checkInfo }}</el-descriptions-item>
          <el-descriptions-item label="检查部位" :span="2">{{ checkRequest.checkPosition || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="3">{{ checkRequest.checkRemark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="placeholder">未找到申请数据</div>
    </el-card>

    <el-card shadow="hover" class="select-card">
      <template #header>确认检查科室与医生</template>
      <el-form :model="form" label-width="100px" class="form-area">
        <el-form-item label="检查科室">
          <el-select v-model="form.deptId" placeholder="选择科室" @change="onDeptChange" filterable style="width:260px">
            <el-option v-for="d in deptList" :key="d.id" :label="d.deptName || d.dept_name" :value="d.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查医生">
          <el-select v-model="form.employeeId" placeholder="先选择科室" filterable style="width:260px">
            <el-option v-for="e in doctorList" :key="e.id" :label="e.realName || e.realname" :value="e.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" :loading="starting" @click="handleStart" :disabled="!canStart">开始检查</el-button>
            <el-button @click="resetSelect">重置</el-button>
            <el-button @click="goBack">返回列表</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchDetail, startCheck } from '@/api/checkRequest'
import request from '@/utils/request'

const router = useRouter()
const requestData = sessionStorage.getItem('current_check_request')
const checkRequest = ref(requestData ? JSON.parse(requestData) : null)
const patient = ref({})

const form = reactive({ deptId: '', employeeId: '' })
const deptList = ref([])
const doctorList = ref([])
const starting = ref(false)

const canStart = computed(()=> !!(checkRequest.value && form.employeeId && ['已开立','已缴费'].includes(checkRequest.value.checkState)) )

async function loadRegisterDetail(){
  if(!checkRequest.value?.registerId) return
  try {
    const res = await request.get(`/registers/id/${checkRequest.value.registerId}`)
    if(res.data){
      patient.value = res.data
    }
  } catch (e){
    console.error(e)
  }
}

async function loadDeptList(){
  try {
    const res = await request.get('/departments')
    deptList.value = res.data || []
  } catch(e){ console.error(e) }
}

async function loadDoctors(deptId){
  try {
    // 使用员工条件查询接口过滤科室
    const res = await request.post('/employees/search', { deptmentId: deptId })
    doctorList.value = res.data || []
  } catch(e){ console.error(e) }
}

function onDeptChange(val){
  form.employeeId = ''
  doctorList.value = []
  if(val) loadDoctors(val)
}

async function handleStart(){
  if(!canStart.value) return
  starting.value = true
  try {
    const resp = await startCheck(checkRequest.value.id, form.employeeId)
    if(resp.code===200){
      ElMessage.success('已开始检查')
      router.push('/check/request')
    } else {
      ElMessage.error(resp.message || resp.msg || '操作失败')
    }
  } catch(e){ console.error(e) } finally { starting.value=false }
}

function resetSelect(){
  form.deptId=''; form.employeeId=''; doctorList.value=[]
}
function goBack(){ router.push('/check/request') }

onMounted(()=>{
  if(!checkRequest.value){
    ElMessage.warning('未选中检查申请');
    router.push('/check/request');
    return
  }
  // 更新最新详情并判断是否已出结果
  fetchDetail(checkRequest.value.id).then(res=>{
    if(res.data){
      checkRequest.value = { ...checkRequest.value, ...res.data }
      if(checkRequest.value.checkState === '已出结果'){
        ElMessage.info('该检查已出结果，无法在此继续操作')
        sessionStorage.removeItem('current_check_request')
        router.push('/check/request')
        return
      }
    }
  })
  // 本地初始状态也做一次快速判断（防止接口延迟）
  if(checkRequest.value.checkState === '已出结果'){
    ElMessage.info('该检查已出结果，无法在此继续操作')
    sessionStorage.removeItem('current_check_request')
    router.push('/check/request')
    return
  }
  loadRegisterDetail()
  loadDeptList()
})
</script>

<style scoped>
.check-patient-page { display:flex; flex-direction:column; gap:16px; padding:16px; }
.patient-card, .select-card { border-radius:12px; }
.card-header { font-weight:600; }
.form-area { max-width:640px; }
.placeholder { color:#999; }
</style>
